trigger updateAccountPrimaryOwner on Account (before insert, before update) {

 List<Account> acctList = new List<Account>();
 List<id> accountOwnerID = new List<id>();
 List<User> AccountOwners = new list<User>();  
 
 ID localAdvertiserRecordTypeID = RecordTypeHelper.GetRecordTypeID('Account', 'Local OOR Customer');
 
 Map<id,id> NewMap = new Map<id,id>();  
 Map<id,id> OldMap = new Map<id,id>();  
 Map<id,String> OwnerMap = new Map<id,String>();  

 
 if(trigger.isInsert){   
          
          for(Account acc :Trigger.new){  
               if(acc.RecordTypeId == localAdvertiserRecordTypeID){    
                       acctList.add(acc);                      
                       accountOwnerID.add(acc.ownerid);       
                                }   
                 }       
         if(accountOwnerID.size()>0){AccountOwners = [select id, name from user where id in :accountOwnerID];}                                

         for(User U : AccountOwners ){        
             OwnerMap.put(U.Id, U.Name);   
                      }    
              
         for(Account acct : acctList){                                      
             acct.Primary_Owner__C =  OwnerMap.get(acct.ownerid);
             acct.Account_Owner_Details__c = acct.ownerid;
                               }   
                }    
 if(Trigger.IsUpdate){    
       
              for(Account acnt :Trigger.New){
              if(acnt.RecordTypeId == localAdvertiserRecordTypeID && acnt.OwnerID!=Trigger.OldMap.get(acnt.Id).OwnerID){        
                                          
                          NewMap.put(acnt.id, acnt.ownerid);            
                          acctList.add(acnt);   
                          accountOwnerID.add(acnt.ownerid);               
                   }    
                }            
                                                           
              for(Account acnt :Trigger.old){           
              if(acnt.RecordTypeId == localAdvertiserRecordTypeID){     
                   OldMap.put(acnt.id, acnt.ownerid);
                   }             
              }                          
                      
          if(accountOwnerID.size()>0){AccountOwners = [select id, name from user where id in :accountOwnerID];}
          
                        for(User U : AccountOwners ){           
                            OwnerMap.put(U.Id, U.Name);    
                           }      
              
              for(Account acnt: acctList){             
             
              if(NewMap.get(acnt.id) != OldMap.get(acnt.id)){                
               acnt.Primary_Owner__C =  OwnerMap.get(acnt.ownerid);   
              acnt.Account_Owner_Details__c = acnt.ownerid;
             
                         }              
                }             
            }        
 
}